import Vue from 'vue'
import Vuex from 'vuex'
import http from '@/api/http'

Vue.use(Vuex)

const tabPage = {
  '/pages/index/index': true,
  '/pages/user/user': true
}
const store = new Vuex.Store({
  strict: true,
  state: {
    userInfo: uni.getStorageSync('userInfo') || null,
    lastRouterInfo: null, // 上一页路由
    scanDateTime: uni.getStorageSync('scanDateTime') || new Date().getTime()
  },
  actions: {
    getUserInfo({ commit, state }, data = {}) {
      console.log(state)
      http({
        url: 'wechatbase/relatedAccount/queryWechatUserInfo',
        data: {},
        header: {
          openId: data.openid || state.userInfo.openid
        },
        method: 'post'
      }).then((res) => {
        console.log(res)
        commit('setUserInfo', { ...state.userInfo, ...res[0], ...data })
      })
    }
  },
  mutations: {
    // 设置登录信息
    setUserInfo(state, data) {
      state.userInfo = data
      uni.setStorageSync('userInfo', data)
      if (state.userInfo.phoneNo) {
        const url = state.lastRouterInfo ? state.lastRouterInfo.fullPath : '/pages/index/index'
        if (tabPage[url]) {
          uni.switchTab({
            url
          })
        } else {
          uni.redirectTo({
            url
          })
        }
      }
    },
    // 判断是否已登录
    judgeUserInfo(state, data) {
      if (state.userInfo && state.userInfo.phoneNo) {
        data.callback()
      } else {
        const pages = getCurrentPages()
        let currPage = null
        if (pages.length) {
          currPage = pages[pages.length - 1]
          if (currPage) {
            state.lastRouterInfo = currPage.$page
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }
        }
      }
    },
    // 设置已弹窗时间
    setScanDateTime(state, data) {
      const nowTime = new Date().getTime()
      state.scanDateTime = nowTime
      uni.setStorageSync('scanDateTime', nowTime)
    },
    // 判断是否需要弹框
    judgeScanDateTime(state, data) {
      // const day = 48 * 60 * 60 * 1000
      const day = 20 * 1000
      const nowTime = new Date().getTime()
      if ((state.scanDateTime + day) < nowTime) {
        data.needFn()
      } else {
        data.unwantedFn()
      }
    }
  }
})

export default store
